package LeetCode热题HOT100;

import java.util.*;

public class p347前K个高频元素 {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int num:nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

        //建立小堆
        Queue<Map.Entry<Integer,Integer>> minHeap=new PriorityQueue<>((o1, o2) -> o1.getValue()-o2.getValue());

        for (Map.Entry<Integer,Integer> entry:map.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size()>k) {
                minHeap.poll();
            }
        }

        int[] res=new int[k];
        for (int i = k-1; i >=0; i--) {
            res[i]=minHeap.poll().getKey();
        }
        return res;

    }
}
